from pydantic import Field
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
    """应用配置"""

    # Flask 配置
    SECRET_KEY: str = Field(default="dev-secret-key-change-in-production")
    DEBUG: bool = Field(default=True)

    # 数据库配置
    MYSQL_HOST: str = Field(default="localhost")
    MYSQL_PORT: int = Field(default=3306)
    MYSQL_USER: str = Field(default="root")
    MYSQL_PASSWORD: str = Field(default="")
    MYSQL_DATABASE: str = Field(default="data_export_service")

    # Redis 配置
    REDIS_HOST: str = Field(default="localhost")
    REDIS_PORT: int = Field(default=6379)
    REDIS_DB: int = Field(default=0)
    REDIS_PASSWORD: str | None = Field(default=None)

    # Celery 配置
    CELERY_BROKER_URL: str = Field(default="redis://localhost:6379/0")
    CELERY_RESULT_BACKEND: str = Field(default="redis://localhost:6379/0")

    # 导出配置
    EXPORT_CHUNK_SIZE: int = Field(default=1000)
    EXPORT_TIMEOUT: int = Field(default=3600)  # 1小时

    LOG_LEVEL: str = Field(default="info")
    LOG_FORMAT: str = Field(default="%(asctime)s %(levelname)s %(message)s")
    LOG_FILE: str = Field(default="logs/app.log")
    LOG_MAX_BYTES: int = Field(default=1024 * 1024 * 10)  # 10MB
    LOG_BACKUP_COUNT: int = Field(default=5)
    LOG_FORMATTER: str = Field(default="json")
    LOG_ROTATION: str = Field(default="100 MB")
    LOG_ENCODING: str = Field(default="utf-8")

    @property
    def database_url(self) -> str:
        """构建数据库连接URL"""
        return f"mysql+pymysql://{self.MYSQL_USER}:{self.MYSQL_PASSWORD}@{self.MYSQL_HOST}:{self.MYSQL_PORT}/{self.MYSQL_DATABASE}"

    @property
    def redis_url(self) -> str:
        """构建Redis连接URL"""
        if self.REDIS_PASSWORD:
            return f"redis://:{self.REDIS_PASSWORD}@{self.REDIS_HOST}:{self.REDIS_PORT}/{self.REDIS_DB}"
        return f"redis://{self.REDIS_HOST}:{self.REDIS_PORT}/{self.REDIS_DB}"

    model_config = {"env_file": ".env", "case_sensitive": True}


# 全局配置实例
settings = Settings()
